from django.db import models
from django.contrib.contenttypes import generic
from base import DataItem, Type, TimeRelation
from core import Person

class InstitutionType(Type):
    class Meta:
        app_label = 'openpolitics'

class Institution(models.Model):
    '''
    Any form of an organized group that serves some purpose and has people serving roles.
    Be it a chamber, political party, state
    '''
    name = models.CharField(max_length=100)
    shortname = models.CharField(max_length=50)
    slug = models.SlugField()
    type = models.ForeignKey(InstitutionType)
    data = generic.GenericRelation(DataItem)
    parents = models.ManyToManyField('self',
                                     symmetrical=False,
                                     through='InstToInstRelation',
                                     related_name='children')

    class Meta:
        app_label = 'openpolitics'

    def __unicode__(self):
        return '%s (%s)' % (self.name, self.type.name)

class InstToInstRelation(TimeRelation):
    '''
    A relation between two institutions
    One instutution may be a parent of another (Poland is a member of European Union)
    '''
    institution = models.ForeignKey(Institution)
    parent = models.ForeignKey(Institution, related_name='parentrels')

    class Meta:
        app_label = 'openpolitics'



class PositionType(Type):
    '''
    Type of a position. It allows for building bridges between different political systems in different countries
    Example: President, Marshal, Prime Minister, Deputy
    '''
    institution = models.ForeignKey(InstitutionType)

    class Meta:
        app_label = 'openpolitics'

    def __unicode__(self):
        return '%s (%s)' % (self.name, self.institution.name)

class Position(models.Model):
    '''
    A position in a given institution of a type described by PositionType.
    For example "Marszalek Sejmu" in Poland
    '''
    name = models.CharField(max_length=50)
    type = models.ForeignKey(PositionType)
    data = generic.GenericRelation(DataItem)
    institution = models.ForeignKey(Institution)
    parents = models.ManyToManyField('self',
                                     symmetrical=False,
                                     through='PosToPosRelation',
                                     related_name='children')
    people = models.ManyToManyField(Person,
                                    symmetrical=False,
                                    through='Term',
                                    related_name='positions')


    class Meta:
        app_label = 'openpolitics'

    def __unicode__(self):
        return '%s (%s)' % (self.name, self.institution.shortname)


class PosToPosRelation(TimeRelation):
    '''
    Relation between positions
    Example: President may have his Advisor
    '''
    position = models.ForeignKey(Position)
    parent = models.ForeignKey(Position, related_name='parentrels')

    class Meta:
        app_label = 'openpolitics'
